package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    /**
     * 创建工单
     *
     * @param taskViewModel
     */
    @Override
    @Transactional
    public Boolean createTask(TaskViewModel taskViewModel) {

        //检验参数
        if (taskViewModel == null
                && taskViewModel.getInnerCode() == null
                && taskViewModel.getUserId() == null) {
            throw new LogicException("参数异常!!");
        }

        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        UserVO user = userService.getUser(taskViewModel.getUserId());

        //检验售货机状态
        checkOutVMStatus(taskViewModel, vmInfo);

        //校验同一台设备是否有未完成同类型工单
        if (checkOrder(taskViewModel)) {
            throw new LogicException("同一台设备存在未完成同类型工单");
        }

        TaskEntity taskEntity = getTaskEntity(taskViewModel, vmInfo, user);
        this.save(taskEntity);

        //更新分数
        updateSetScore(user,1);

        //如果是补货工单，插入补货详情表数据
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
            insertTaskDetailData(taskViewModel, taskEntity);
        }

        return Boolean.TRUE;
    }

    /**
     * 更新分数
     *
     * @param user 用户信息
     */
    private void updateSetScore(UserVO user,Integer score) {
        String redisKey = VMSystem.REGION_TASK_KEY_PREF
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "."
                + user.getRegionId() + "."
                + user.getRoleCode();
        redisTemplate.opsForZSet().incrementScore(redisKey, user.getUserId(), score);
    }

    /**
     * 接受工单
     *
     * @param taskId 工单Id
     * @param userId 当前登录用户Id
     * @return Boolean
     */
    @Override
    public Boolean acceptTask(long taskId, Integer userId) {

        //查询工单信息
        TaskEntity entity = this.getById(taskId);

        //如果工单不是待处理状态，抛出异常
        if (!Objects.equals(entity.getTaskStatus(), VMSystem.TASK_STATUS_CREATE)) {
            throw new LogicException("当前工单不是待处理状态，请勿接单");
        }

        //判断执行工单的执行人是否为当前登录用户
        if (!Objects.equals(entity.getUserId(), userId)) {
            throw new LogicException("您不是当前工单的执行人，请勿接单");
        }

        //将工单状态改为进行中
        entity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);

        //执行修改语句
        this.updateById(entity);

        return Boolean.TRUE;
    }

    /**
     * 取消/拒绝工单
     *
     * @param taskId
     * @param model
     * @return
     */
    @Override
    public Boolean cancelTask(long taskId, CancelTaskViewModel model) {

        //查询工单信息
        TaskEntity entity = this.getById(taskId);

        //如果工单状态是已取消或已完成，抛出异常
        if (Objects.equals(entity.getTaskStatus(), VMSystem.TASK_STATUS_CANCEL)
                || Objects.equals(entity.getTaskStatus(), VMSystem.TASK_STATUS_FINISH)) {
            throw new LogicException("当前工单已结束，请勿重复操作");
        }

        //判断工单执行人是否为当前登录用户/工单指派人
        if (!Objects.equals(entity.getUserId(), model.getUserId())
                && !Objects.equals(entity.getAssignorId(), model.getUserId())) {
            throw new LogicException("您不是当前工单的执行人/指派人，不能进行此类操作");
        }

        //修改工单状态为取消
        entity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        //记录取消/拒绝原因
        entity.setDesc(model.getDesc());

        //执行修改
        this.updateById(entity);
        //获取user信息
        UserVO user = userService.getUser(entity.getUserId());
        //更新分数
        updateSetScore(user,-1);

        return Boolean.TRUE;
    }

    /**
     * 完成工单
     *
     * @param taskId 工单Id
     * @param userId 当前登录用户Id
     * @return
     */
    @Override
    public Boolean completeTask(long taskId, Integer userId) {

        //查询工单信息
        TaskEntity entity = this.getById(taskId);

        //判断工单状态是否是进行中，如果不是抛出异常
        if (!Objects.equals(entity.getTaskStatus(), VMSystem.TASK_STATUS_PROGRESS)) {
            throw new LogicException("当前工单无法点击完成，请勿重复操作");
        }

        //判断工单执行人是否为当前登录用户
        if (!Objects.equals(entity.getUserId(), userId)) {
            throw new LogicException("您不是当前工单执行人，请勿重复操作");
        }

        //将工单状态改为已完成
        entity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        this.updateById(entity);

        //投放工单完成后将售货机状态更改为  运营 状态
        //撤机工单：完成后将售货机状态更改为  撤机 状态
        sendOpsCompleteTaskMsg(entity);

        if (Objects.equals(entity.getProductTypeId(), VMSystem.TASK_TYPE_SUPPLY)) {
            try {
                List<TaskDetailsEntity> taskDetailsEntities = taskDetailsService.getByTaskId(entity.getTaskId());
                List<SupplyChannel> collect = taskDetailsEntities.stream().map(each -> {
                    SupplyChannel supplyChannel = new SupplyChannel();
                    BeanUtils.copyProperties(each, supplyChannel);
                    supplyChannel.setChannelId(each.getChannelCode());
                    supplyChannel.setCapacity(each.getExpectCapacity());
                    return supplyChannel;
                }).collect(Collectors.toList());
                SupplyContract supplyContract = new SupplyContract();

                supplyContract.setInnerCode(entity.getInnerCode());
                supplyContract.setSupplyData(collect);

                mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }


        return Boolean.TRUE;
    }

    /**
     * 获取最少工单人员信息
     * @param regionId 区域ID
     * @param isSupply false 运营工单 true 运维工单
     * @return 用户id  if get nothing, return null
     */
    @Override
    public Integer getLeastUser(Long regionId,Boolean isSupply) {

        String roleCode= "1003";
        //运维传true，运营传false
        if (!isSupply){
            roleCode="1002";
        }

        String redisKey = VMSystem.REGION_TASK_KEY_PREF
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "."
                + regionId + "."
                + roleCode;

        Set<Object> range = redisTemplate.opsForZSet().range(redisKey, 0, 0);

        if (CollectionUtils.isEmpty(range)){
            return null;
        }

        return (Integer) new ArrayList<>(range).get(0);
    }

    /**
     * 运维工单完成后通过EMQ异步调用修改售货机状态
     *
     * @param entity
     */
    private void sendOpsCompleteTaskMsg(TaskEntity entity) {
        if (Objects.equals(entity.getProductTypeId(), VMSystem.TASK_TYPE_DEPLOY)
                || Objects.equals(entity.getProductTypeId(), VMSystem.TASK_TYPE_REVOKE)) {
            TaskCompleteContract contract = new TaskCompleteContract();
            contract.setTaskType(entity.getProductTypeId());
            contract.setInnerCode(entity.getInnerCode());
            try {
                mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, contract);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 校验同一台设备是否有未完成同类型工单
     *
     * @param taskViewModel
     */
    private Boolean checkOrder(TaskViewModel taskViewModel) {
        QueryWrapper<TaskEntity> queryWrapper = new QueryWrapper<TaskEntity>();
        queryWrapper.lambda().select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode())
                .eq(TaskEntity::getProductTypeId, taskViewModel.getProductType())
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(queryWrapper) > BigDecimal.ZERO.intValue();
    }

    /**
     * 检验售货机状态
     *
     * @param taskViewModel
     * @param vmInfo
     */
    private void checkOutVMStatus(TaskViewModel taskViewModel, VmVO vmInfo) {
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_DEPLOY
                && Objects.equals(vmInfo.getStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机为运营状态，无法投放！！");
        }
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY
                && !Objects.equals(vmInfo.getStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机不是运营状态，无法补货！！");
        }
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_REVOKE
                && !Objects.equals(vmInfo.getStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机不是运营状态，无法撤机！！");
        }
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_REPAIR
                && !Objects.equals(vmInfo.getStatus(), VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("当前售货机不是运营状态，无法维修！！");
        }
    }

    /**
     * 向补货详情表批量插入数据
     *
     * @param taskViewModel
     * @param taskEntity
     */
    private void insertTaskDetailData(TaskViewModel taskViewModel, TaskEntity taskEntity) {

        List<TaskDetailsEntity> collect = taskViewModel.getDetails().stream().map(each -> {
            TaskDetailsEntity taskDetails = new TaskDetailsEntity();
            taskDetails.setTaskId(taskEntity.getTaskId());
            BeanUtils.copyProperties(each, taskDetails);
            return taskDetails;
        }).collect(Collectors.toList());

        taskDetailsService.saveBatch(collect);
    }

    /**
     * 拷贝工单数据
     *
     * @param taskViewModel 前端传入参数
     * @param vmInfo        售货机信息
     * @param user          执行人信息
     * @return
     */
    private TaskEntity getTaskEntity(TaskViewModel taskViewModel, VmVO vmInfo, UserVO user) {
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        taskEntity.setTaskCode(generateTaskCode());
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setRegionId(vmInfo.getRegionId());
        taskEntity.setUserName(user.getUserName());
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        taskEntity.setAddr(vmInfo.getNodeAddr());
        return taskEntity;
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

}
